<template>
<!-- 指标选项 -->
  <div class="indic-cascader">
    <el-cascader size="small" :value="val" :options="options" :props="{ multiple: true,emitPath:false }" collapse-tags :show-all-levels="false" popper-class="indicator" v-bind="$attrs" @input="indicatorInput" @change="indicatorChange"></el-cascader>
  </div>
</template>

<script type="text/javascript">
export default {
  name: 'IndicCascader',
  components: {},
  props: {
    value: {
      type: Array,
      required: true
    },
    options: {
      type: Array,
      required: true
    },
    defIndic: {
      type: Array,
      default: () => ([])
    }
  },
  data () {
    return {
      val: []
    }
  },
  methods: {
    indicatorInput (newVal) {
      const { val: oldVal } = this
      newVal = newVal.slice()
      const diff = newVal.length - oldVal.length
      const defaultVal = -1
      if (diff > 0) {
        // 选项增加
        const add = newVal.filter(v => !oldVal.includes(v))
        // 包括默认
        if (add.includes(defaultVal)) {
          this.defIndic.forEach(val => {
            if (!newVal.includes(val)) {
              newVal.push(val)
            }
          })
        } else if (!newVal.includes(defaultVal) && this.defIndic.every(val => newVal.includes(val))) {
          newVal.push(defaultVal)
        }
      } else if (diff < 0) {
        // 选项减少
        const minus = oldVal.filter(v => !newVal.includes(v))
        // 包括默认
        if (minus.includes(defaultVal)) {
          newVal = newVal.filter(val => !this.defIndic.includes(val))
        } else if (newVal.includes(defaultVal) && this.defIndic.some(val => !newVal.includes(val))) {
          newVal = newVal.filter(val => val !== defaultVal)
        }
      }
      this.val = newVal
      diff !== 0 && this.$emit('input', newVal)
    },
    indicatorChange (val) {
      this.$emit('change', val)
    }
  },
  watch: {
    defIndic () {
      this.indicatorInput(this.value)
    }
  }
}
</script>

<style lang="scss" scoped>
.indic-cascader {
  display: inline-block;
}
</style>
<style lang="scss" >
.el-popper.indicator {
  .el-checkbox__input.is-indeterminate .el-checkbox__inner {
    border-color: #6eb5ff;
    background-color: #6eb5ff;
  }
}
</style>
